﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.IO;
using System.Windows.Media;
using System.Drawing;
using System.Drawing.Imaging;
using FreeImageAPI;
using FreeImageAPI.Metadata;


namespace Iris.ImageProcess
{
    class FreeImageHelper
    {

        public static ImageSource ReadImage(FileInfo file) {

            FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
            Bitmap bitmap = FreeImage.LoadBitmap(file.FullName, FREE_IMAGE_LOAD_FLAGS.JPEG_FAST , ref format);
            
            return ToWpfBitmap(bitmap);
            

        }

        private static BitmapImage ToWpfBitmap(Bitmap bitmap)
        {
            // https://bitbucket.org/breki74/tutis/src/92eeb767795136805cc2c1cc3636762662350c17/Experimental/GisExperiments/GisExperiments/WpfImaging/WpfImagingTests.cs
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Bmp);

                stream.Position = 0;
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
                // Force the bitmap to load right now so we can dispose the stream.
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.StreamSource = stream;
                result.EndInit();
                result.Freeze();
                return result;
            }
        }
        
    }
}
